#!/usr/bin/env python
# -*- coding=utf-8 -*-
import sys
import os

from utils import sample_info_parse,TitleParser

sample_info = sys.argv[1]
adv_dir = sys.argv[2]
odir = sys.argv[3]

def find_sample_SV(info_dict,path,odir):
    """
    Find the identical SV in family memebers
    SV or CNV
    """
    for category in ["SV","CNV"]:
        for fid in info_dict:
            members = list(info_dict[fid])
            member_number = len(members)
            fid_dict = {}
            for people in members:
                sv_file = "{people}.LikelyDeleterious.{category}.xls".format(
                    people=people,category=category,
                )
                if category == "SV":
                    dir_name = 'FilterSV'
                elif category == "CNV":
                    dir_name = 'FilterCNV'
                sv_path = os.path.join(path,dir_name,people,sv_file)
                with open(sv_path,'r') as indata:
                    title = indata.readline()
                    tp = TitleParser(title)
                    for line in indata:
                        line_list = line.strip().split('\t')
                        chrom = tp.get_field(line_list,"Chr")
                        start = tp.get_field(line_list,"Start")
                        end = tp.get_field(line_list,"End")
                        if category == "CNV":
                            svtype = tp.get_field(line_list,"CNVType")
                        elif category == "SV":
                            svtype = tp.get_field(line_list,"SVType")
                        if svtype != "breakpoint":
                            if (chrom,start,end,svtype) not in fid_dict:
                                fid_dict[(chrom,start,end,svtype)] = {
                                    "line":line,
                                    "count":1,
                                }
                            else:
                                fid_dict[(chrom,start,end,svtype)]['count'] +=1
            ofile = "{fid}.LikelyDeleterious.identical_{category}.xls".format(
                fid = fid, category = category
            )
            opath = os.path.join(odir,ofile)
            with open(opath,'w') as odata:             
                odata.write(title)       
                for item in fid_dict:
                    if fid_dict[item]['count'] == member_number:
                       odata.write(fid_dict[item]['line'])
            print('Output idential SV to file {ofile}'.format(ofile=opath))

if __name__ == "__main__":
    info_dict = sample_info_parse(sample_info)
    find_sample_SV(info_dict,adv_dir,odir)